package com.tl.test;

import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;

/**
 * 提交参数演示 该程序连接到一个用于查询手机号码所属地的页面 以便查询号码段1330227所在的省份以及城市
 * 
 * @authorLiudong
 */
public class SimpleHttpClient {

	public static void main(String[] args) throws IOException {
		
		//http://www.ip138.com:8080/search.asp?action=mobile&mobile=13701167064
		HttpClient client = new HttpClient();
		client.getHostConfiguration().setHost("www.ip138.com", 8080, "http");
		HttpMethod method = getPostMethod(); // 使用 POST 方式提交数据
		client.executeMethod(method); // 打印服务器返回的状态
		System.out.println(method.getStatusLine()); // 打印结果页面
		String response = new String(method.getResponseBodyAsString().getBytes("gb2312"));		
//		String response = method.getResponseBodyAsString();

		// 打印返回的信息
		System.out.println(response);
		method.releaseConnection();
	}

	/**
	 * 使用 GET 方式提交数据
	 * 
	 * @return
	 */

	private static HttpMethod getGetMethod() {
		return new GetMethod("/search.asp?action=mobile&mobile=13701167064");
	}

	/**
	 * 使用 POST 方式提交数据
	 * 
	 * @return
	 */
	private static HttpMethod getPostMethod() {
		PostMethod post = new PostMethod("/search.asp");
		NameValuePair simcard = new NameValuePair("action", "mobile");
		NameValuePair simcard2 = new NameValuePair("mobile", "13701167064");
		post.setRequestBody(new NameValuePair[] { simcard,simcard2 });
		return post;
	}
}
